package com.dayatang.exam.domain;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.SortType;

/**
 * 多�?�?
 * 
 * @author yang
 * 
 */
@Entity
@DiscriminatorValue("MC")
public class MultiChoiceQuestion extends Question implements ObjectiveQuestion {

	private static final long serialVersionUID = -2115703999982112311L;

	/**
	 * 选择�?
	 */
	@org.hibernate.annotations.CollectionOfElements
	@JoinTable(name = "QUESTION_OPTIONS", joinColumns = @JoinColumn(name = "QUESTION_ID"))
	@org.hibernate.annotations.MapKey(columns = @Column(name = "CODE", nullable = false))
	@org.hibernate.annotations.Sort(type = SortType.NATURAL)
	@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
	private Map<String, QuestionOption> options = new TreeMap<String, QuestionOption>();

	public Map<String, QuestionOption> getOptions() {
		return options;
	}

	public void setOptions(Map<String, QuestionOption> options) {
		this.options = options;
	}

	public void addOption(String key, QuestionOption option) {
		options.put(key, option);
	}

	@Override
	public String getTypeName() {
		return Question.TYPE_MULTI_CHOICE;
	}

	@Override
	public void save() {
		setSolution(prepareSolution(getSolution()));
		super.save();
	}

	private String prepareSolution(String data) {
		String result = data;
		result = result.replaceAll(",", "");
		result = result.replaceAll("，", "");
		result = result.replaceAll(" ", "");
		result = result.replaceAll("　", "");
		return result;
	}

	public boolean isCorrect(String answer) {
		return toCharSet(answer).equals(toCharSet(getSolution()));
	}

	/**
	 * 
	 * @param data
	 * @return
	 */
	private Set<String> toCharSet(String data) {
		Set<String> result = new HashSet<String>();
		if (data != null && !data.isEmpty()) {
			for (int i = 0; i < data.length(); i++) {
				result.add(String.valueOf((data.charAt(i))));
			}
		}
		return result;
	}
	
	public static MultiChoiceQuestion get(Long id) {
		return getRepository().get(MultiChoiceQuestion.class, id);
	}
}
